<template>
  <div class="card-container">
    <Row :gutter="40">
      <Col :span="18">
        <Form
          :model="queryWarnParams"
          ref="queryWarnForm"
          :inline="true"
          :labelCol="{ span: 6 }"
          :wrapperCol="{ span: 20 }"
        >
          <Row :gutter="20">
            <Col :span="8">
              <FormItem label="事件ID" name="eewId">
                <Input
                  v-model:value="queryWarnParams.eewId"
                  placeholder="请输入事件ID"
                  allowClear
                  @keyup.enter.native="handleWarnQuery"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="时间" name="warnSearchTime">
                <RangePickerCom
                  v-model:timeValue="queryWarnParams.warnSearchTime"
                  @updateDate="handleDateUpdate"
                ></RangePickerCom>
                <!-- @keyup.enter.native="handleQuery" -->
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="消息类型" name="msgType">
                <Select
                  v-model:value="queryWarnParams.msgType"
                  :options="sysMsgTypeOptions"
                  allowClear
                  placeholder="请选择消息类型"
                ></Select>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Col>

      <Col :span="6">
        <Flex justify="end">
          <Space>
            <b-button icon="refresh" size="small" @click="resetWarnQuery">
              重置</b-button
            >
            <b-button icon="search" size="small" @click="handleWarnQuery(true)"
              >平台记录
            </b-button>
            <b-button icon="search" size="small" @click="handleWarningTogether"
              >设备记录
            </b-button>
          </Space>
        </Flex>
      </Col>
    </Row>
  </div>
  <div
    class="card-container max-h-full overflow-y-auto yqy-border-padding"
    v-if="warnTabData.length > 0"
  >
    <Collapse
      v-if="warnTabData.length > 0"
      :bordered="false"
      class="warning-collapse"
      v-model:activeKey="activeKeys"
    >
      <CollapsePanel
        v-for="item in warnTabData"
        :key="'warn' + item.eewId"
        @click.native="handleExpandChange(item)"
      >
        <template #header>
          <div class="collapse-title">
            <div style="min-width: 220px">
              <span>事件ID：</span>
              <span> {{ item.eewId }}</span>
            </div>
            <div style="min-width: 150px">
              <span>消息类型：</span>
              <span>{{ formatType(item.msgType) }}</span>
            </div>
            <div style="min-width: 170px">
              <span>消息来源：</span>
              <span> {{ item.msgSource }}</span>
            </div>
            <div style="min-width: 190px">
              <span>消息生产者：</span>
              <span>{{ item.producer }}</span>
            </div>
            <div>
              <span>报数：</span>
              <span> {{ item.count }}</span>
            </div>
            <div class="ml-[20px]" v-show="item.checkViedo">
              <span @click.stop="handleWarnView(item)">预警上传资料</span>
            </div>
          </div>
        </template>
        <!-- <div v-if="item.viewTableList.length > 0"> -->
        <div
          class="collapse-content"
          v-for="(val, index) in item.viewTableList"
          :key="'warn_' + index + val.msgId"
        >
          <div class="collapse-top">
            <div class="left flex">
              <span>消息ID:</span>
              <span>{{ val.msgId }}</span>
              <SvgIcon
                v-if="val.msgType != '0199'"
                :name="formatLevel(val.localWarningLevel)"
                class="w-[112px] h-[30px] mr-1"
                :color="formatColor(val.localWarningLevel)"
                :strokeColor="formatColor(val.localWarningLevel)"
              />
              <SvgIcon
                :name="val.isResponse == '已响应' ? 'responded' : 'unresponse'"
                class="w-[112px] h-[30px] mr-1"
                :color="val.isResponse == '已响应' ? '#6AD7CA' : '#FF5368'"
                :strokeColor="
                  val.isResponse == '已响应' ? '#6AD7CA' : '#FF5368'
                "
              />
            </div>
            <div class="right">
              <span @click="handleWarnMessage(val)">消息</span>
              <span @click="handleWarnReceive(val)">回复</span>
              <span
                v-show="val.msgType != '0199'"
                @click="handleWarnRespon(val)"
                >响应</span
              >
            </div>
          </div>
          <div class="collapse-bottom">
            <div>
              <!-- <svg-icon icon-class="red" /> -->
              {{
                val.msgType == '0199'
                  ? '取消消息'
                  : val.serialNumber == '1'
                    ? '首报'
                    : '第' + val.serialNumber + '报'
              }}
            </div>
            <div>
              <span>震级:</span>
              <span>{{ val.magnitude == 'null' ? '-' : val.magnitude }}</span>
            </div>
            <div>
              <span>震中烈度:</span>
              <span>{{
                val.epiintensity == 'null' ? '-' : val.epiintensity
              }}</span>
            </div>
            <div>
              <span>震源深度:</span>
              <span>{{ val.focdepth == 'null' ? '-' : val.focdepth }}</span>
            </div>
            <div>
              <span>发震时间: </span>
              <span>{{ val.oritimeStr == 'null' ? '-' : val.oritimeStr }}</span>
            </div>
            <div>
              <span>震中地名:</span>
              <span>{{ val.locname == 'null' ? '-' : val.locname }}</span>
            </div>
          </div>
        </div>
        <!-- </div> -->
      </CollapsePanel>
    </Collapse>
  </div>

  <Pagination
    v-if="warnTotal > 0"
    :total="warnTotal"
    v-model:current="queryWarnParams.pageNum"
    v-model:pageSize="queryWarnParams.pageSize"
    :changeApi="getWarnList"
  ></Pagination>
  <!-- 查看报文弹窗 -->
  <ReportModal
    v-if="reportVisible"
    v-model:report-visible="reportVisible"
    :titles="titles"
    :message-data="messageData"
  ></ReportModal>

  <!-- 预警资料弹窗 -->
  <Modal
    title="上传"
    v-model:open="warnVisible"
    width="40%"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <div class="file-box">
      <div class="file-item" v-for="(n, index) in fileList" :key="index">
        <div class="menu file-item-object">
          <Row type="flex" justify="space-between">
            <Col :span="20">
              <div class="file-item-content">
                <SvgIcon name="file" class="svg-icon" />
                <div class="file-name">
                  <div>
                    <span class="file-logo">{{ formatLogo(n.name) }}</span>
                    <span>{{ getFileName(n.name) }}</span>
                  </div>
                  <div>
                    <span style="margin-right: 30px">{{
                      moment(n.lastModified).format('YYYY-MM-DD HH:mm:ss')
                    }}</span>
                    <span> {{ formatSize(n.size) }}</span>
                  </div>
                </div>
              </div>
            </Col>
            <Col
              :span="4"
              style="text-align: right; font-size: 20px"
              class="flex items-center"
            >
              <SvgIcon
                class="svg-icon"
                style="margin-right: 20px"
                name="down-file"
                @click="handleFileDown(n)"
              />
            </Col>
          </Row>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script setup lang="tsx">
import { ref } from 'vue';
import {
  Col,
  Collapse,
  CollapsePanel,
  Flex,
  Form,
  FormItem,
  Input,
  Modal,
  Row,
  Select,
  Space,
  message,
} from 'ant-design-vue';
import moment from 'moment';
import minioClient from '@/plugins/minio';
import Pagination from '@/components/Pagination/Index.vue';
import SvgIcon from '@/components/SvgIcons/Index.vue';
import { listToEnum, listToOption } from '@/utils/utils';
import {
  getDeviceWarningList,
  getListByEewId,
  getWarningMessage,
} from '@/api/device';
import { fetchDictsOfType } from '@/api/dict';
import RangePickerCom from './RangePickerCom.vue';
import ReportModal from './ReportModal.vue';

const activeKeys = ref([]);
// 时间框点击清除按钮
const handleDateUpdate = (newDate: any) => {
  queryWarnParams.value.warnSearchTime = newDate;
  queryWarnParams.value.startTime = newDate;
  queryWarnParams.value.endTime = newDate;
};

interface Props {
  pageData: any;
}
const props = defineProps<Props>();

const sysMsgTypeOptions = ref<Global.Option[]>([]);
fetchDictsOfType(['sys_msg_type']).then((res: any) => {
  const { sys_msg_type } = res.data;
  sysMsgTypeOptions.value = listToOption(
    sys_msg_type,
    'dictLabel',
    'dictValue',
  );
});

const formatLevel = (val: string) => {
  switch (val) {
    case '红色预警':
      return 'red';
    case '橙色预警':
      return 'orange';
    case '黄色预警':
      return 'yellow';
    case '蓝色预警':
      return 'blue';
    default:
      return 'none';
  }
};
const formatColor = (val: string) => {
  switch (val) {
    case '红色预警':
      return '#FF5368';
    case '橙色预警':
      return '#FFA318';
    case '黄色预警':
      return '#FFE02C';
    case '蓝色预警':
      return '#0194FF';
    default:
      return 'none';
  }
};

const queryWarnParams = ref({
  pageNum: 1,
  pageSize: 10,
  eewId: null,
  msgSource: null,
  warnSearchTime: null,
  startTime: null,
  endTime: null,
  msgType: null,
  msgIds: null,
  // type: 1,
});
// 预警条件查询
const handleWarnQuery = (item: any) => {
  activeKeys.value = [];
  if (item) {
    queryWarnParams.value.msgIds = null;
  }
  queryWarnParams.value.pageNum = 1;
  if (queryWarnParams.value.warnSearchTime) {
    queryWarnParams.value.startTime = queryWarnParams.value.warnSearchTime[0];
    queryWarnParams.value.endTime = queryWarnParams.value.warnSearchTime[1];
  }
  getWarnList();
};

// 获取预警列表
const warnLaod = ref(false);
const warnTotal = ref(0);
const warnTabData = ref([]);
const getWarnList = async () => {
  warnLaod.value = true;
  queryWarnParams.value.code = props.pageData.code;
  const res: any = await getWarningMessage(queryWarnParams.value);
  if (res.code == 200) {
    warnLaod.value = false;
    warnTotal.value = res.total;
    res.rows.forEach((item: any) => {
      item.viewTableList = [];
      // 获取该bucket下的所有对象
      const objectsStream = minioClient.listObjects(
        'yjzd',
        props.pageData.code + '/Events/' + item.eewId,
        true,
      );
      // 定义一个数组来保存所有对象路径
      const objects: any = [];
      objectsStream.on('data', (object: any) => {
        objects.push(object);
      });
      // 在流结束时输出所有对象的路径
      objectsStream.on('end', () => {
        console.log(objects, 'objects');
        if (objects.length > 0) {
          let _arr = objects;
          // .filter((item) => {
          //     return (
          //         item.name.indexOf('png') == -1
          //         // &&
          //         // item.name.indexOf('txt') == -1
          //     )
          // })
          if (_arr.length > 0) {
            item.file = _arr;
            item.checkViedo = true;
          } else {
            item.checkViedo = false;
          }
        } else {
          return (item.checkViedo = false);
        }
      });
      // 遇到错误时输出错误信息
      objectsStream.on('error', (err: any) => {
        console.log(err);
      });
      // item.viewTableList = [];
      // getListByEewId({ code: this.pageData.code, eewId: item.eewId }).then(
      //   (res) => {
      //     if (res.code == 200) {
      //       // res.data.forEach((row) => {
      //       //     item.viewTableList.push(row);
      //       // });
      //       item.viewTableList = res.data;
      //     }
      //   }
      // );
    });
    // this.$nextTick(()=>{
    setTimeout(() => {
      warnTabData.value = res.rows;
    }, 200);

    console.log(warnTabData.value, ' warnTabData.value');
    // })
  }
};
getWarnList();

// 预警条件查询重置
const queryWarnForm = ref();
const resetWarnQuery = () => {
  queryWarnForm.value.resetFields();
  handleWarnQuery(true);
};
// 预警消息
const handleWarnMessage = (record: any) => {
  titles.value = '报文';
  messageData.value = JSON.parse(record.receiveMessage);
  reportVisible.value = true;
};
// 预警回复
const handleWarnReceive = (record: any) => {
  titles.value = '报文';
  messageData.value = JSON.parse(record.replyMessage);
  reportVisible.value = true;
};
// 同步设备预警查询
const handleWarningTogether = async () => {
  activeKeys.value = [];
  // this.queryWarnParams.code = this.pageData.code;
  const res = await getDeviceWarningList({ code: props.pageData.code });
  if (res.code == 200) {
    if (res.msg == '') {
      warnTabData.value = [];
      warnTotal.value = 0;
      return;
    }
    queryWarnParams.value.msgIds = res.msg as any;
    handleWarnQuery(false);
  }
};
// 预警响应
const handleWarnRespon = (record: any) => {
  // this.messageData = JSON.parseObject(row.statisticsMessage)

  let dataMaps = JSON.parse(record.statisticsMessage);
  for (let key in dataMaps) {
    if (dataMaps['设备型号'] == 'BOEY-ZD10') {
      dataMaps['设备型号'] = 'BOEY-A2';
    } else if (dataMaps['设备型号'] == 'BOEY-ZD05') {
      dataMaps['设备型号'] = 'BOEY-A1';
    } else if (dataMaps['设备型号'] == 'BOEY-ZD02') {
      dataMaps['设备型号'] = 'BOEY-G2';
    }
  }
  titles.value = '报文';
  messageData.value = dataMaps;
  reportVisible.value = true;
};

const reportVisible = ref(false);
const titles = ref('');
const messageData = ref({});

const fileList = ref([]);
const warnVisible = ref(false);
const handleWarnView = (val: any) => {
  console.log(val, 'val');
  fileList.value = val.file;
  warnVisible.value = true;
};

//
const formatLogo = (val: any) => {
  if (val.indexOf('mp4') != -1) {
    return '预警录像';
  } else if (val.indexOf('jpg') != -1 || val.indexOf('png') != -1) {
    return '预警截屏';
  } else if (val.indexOf('mseed') != -1) {
    return '事件波形';
  } else if (val.indexOf('amr') != -1 || val.indexOf('wav') != -1) {
    return '预警录音';
  } else if (val.indexOf('txt') != -1) {
    return '日志文件';
  }
};

//  文件大小格式化
const formatSize = (fileSizeInBytes: any) => {
  const sizeUnit = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const sizeType = parseInt(
    Math.floor(Math.log(fileSizeInBytes) / Math.log(1024)).toString(),
  );
  console.log('sizeType', sizeType);
  const size = (fileSizeInBytes / Math.pow(1024, sizeType)).toFixed(2);
  return size + sizeUnit[sizeType];
};

// 下载视频文件
const handleFileDown = (record: any) => {
  const backetName = 'yjzd';
  minioClient.getObject(
    backetName,
    record.name,
    (err: any, dataStream: any) => {
      if (err) return message.error(err);
      const arr: any = [];
      let size = 0;
      dataStream.on('data', (chunk: any) => {
        if (chunk.length > 0) {
          arr.push(chunk);
          size += chunk.length;
        }
      });
      dataStream.on('end', () => {
        const u8arr = new Uint8Array(size);
        let u8arrIndex = 0;
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr[i].length; j++) {
            u8arr[u8arrIndex] = arr[i][j];
            u8arrIndex += 1;
          }
        }
        const arrBuffer = u8arr.buffer;
        const blob = new Blob([arrBuffer]);
        const blobUrl = URL.createObjectURL(blob);
        const fileName = getFileName(record.name);
        const a = document.createElement('a');
        a.setAttribute('href', blobUrl);
        a.setAttribute('download', fileName);
        a.click();
      });
      dataStream.on('error', (er: any) => {
        message.error(er);
      });
    },
  );
};

const getFileName = (url: string) => {
  // 通过最后一个斜杠将URL分割成数组
  var parts = url.split('/');
  // 获取数组中最后一个元素
  var fileName = parts[parts.length - 1];
  // 返回文件名
  return fileName;
};

// 表格展开
const handleExpandChange = (record: any) => {
  if (record.viewTableList.length == 0) {
    // 获取列表数据
    getListByEewId({
      code: props.pageData.code,
      eewId: record.eewId,
    }).then((res: any) => {
      if (res.code == 200) {
        // 遍历数据，将数据添加到row.viewTableList中
        res.data.forEach((item: any) => {
          record.viewTableList.push(item);
        });
      }
    });
    // }
  }
};

const formatType = (val: string) => {
  switch (val) {
    case '0101':
      return '正式预警';
    case '0201':
      return '演练预警';
    case '0202':
      return '演练预警';
    case '0301':
      return '测试预警';
    case '0199':
      return '取消消息';

    default:
      break;
  }
};
</script>

<style lang="scss" scoped>
.collapse-title {
  position: relative;
  display: flex;

  > div {
    font-size: 16px;
    margin-right: 20px;

    > span:last-child {
      color: var(--custom-sever-info);
    }
  }
}

.down-box {
  position: absolute;
  right: 4%;

  > span {
    margin-left: 20px;
    color: var(--custom-sever-info);
  }
}

.collapse-content {
  padding: 10px 0;
  border-bottom: 1px dashed var(--custom-collapse-content);
}

.collapse-content:last-child {
  border-bottom: none;
}

.collapse-top {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    // display: flex;
    // align-items: center;
    color: var(--text-color);
    font-size: 18px;
    font-weight: 600;

    > span:nth-child(2) {
      margin-right: 20px;
    }
  }

  .right {
    color: var(--custom-sever-info);
    cursor: pointer;

    > span {
      margin: 0 10px;
    }

    > span:hover {
      color: rgba(106, 215, 202, 1);
    }
  }
}

.collapse-bottom {
  margin-top: 20px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: var(--custom-sever-info);
  line-height: 14px;
  height: 14px;

  > div {
    margin: 0 10px;
    > span {
      font-size: 14px;
    }
  }

  > div:first-child {
    font-size: 14px;
    margin-left: 0;
  }
}

.file-box {
  margin-top: 30px;
  padding: 0 20px;
}

.file-item {
  /* width: 10%; */
  /* height: 100px; */
  margin: 10px;
  position: relative;
  overflow: hidden;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.file-path {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  padding: 10px;

  span:hover {
    color: #6ad7ca;
    cursor: pointer;
  }
}

.file-item-object {
  // display: flex;
  // // justify-content: space-between;
  // align-items: center;
  width: 100%;
  height: 100%;
  font-weight: 600;

  cursor: pointer;
  overflow: hidden;
  // border-bottom: 1px solid #ebebeb;
}
.file-item-content {
  display: flex;
  align-items: center;
  line-height: 25px;
}
.file-name {
  /* text-align: center; */
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-left: 12px;
  color: #fff;

  > div:last-child,
  .file-logo {
    font-weight: 400;
    font-size: 14px;
    color: #ffffff99;
  }
  .file-logo {
    display: inline-block;
    color: #fff;
    margin-right: 12px;
    padding: 2px 8px;
    background-color: #5c5c5c;
  }
}
.file-item-object i {
  font-size: 20px;
}
.file-item .svg-icon {
  width: 36px;
  height: 36px;
}
</style>
